//
//  YDBaseTabBarController.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/20.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "YDBaseTabBarController.h"
#import "YDTabBar.h"
#import "YDBaseNavigationController.h"
#import "YDHomeViewController.h"
#import "YDOptionalViewController.h"
#import "YDMineViewController.h"
#import "YDPositionViewController.h"
#import "YDLoginController.h"
#import "YDNewsViewController.h"
#import "YDPositionViewController.h"
#import "YDBaseOptionsViewController.h"
#import "YDLiveViewController.h"


#import "UITabBar+SYBadge.h"


@interface YDBaseTabBarController ()

@property (nonatomic, assign)NSInteger currentIndex;

@property (nonatomic, assign)NSInteger alertCount;


@end

@implementation YDBaseTabBarController

#pragma mark 系统方法


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)init
{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenOver) name:kNoTokenNoti object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(laHeiReslove) name:kNoTeLaHei object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buySuccess:) name:kBuySuccessNoti object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showRedPoint:) name:kShowRedPointNoti object:nil];
        //期权申购成功
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(optionsBuySuccess:) name:kOptionsBuySuccessNoti object:nil];
        //商店更新
//        if ([SYVersionManger sharedInstance].isCannormalJumpTab) {
//            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateVersion) name:UIApplicationDidBecomeActiveNotification object:nil];
//        }
        
        //企业版的更新
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkVersionInformation) name:UIApplicationDidBecomeActiveNotification object:nil];

        _alertCount = 0;
    }
    return self;
}

-(void)tokenOver
{
    if ([SYUserInformation sharedInstance].isLogin) {
        [self presentLoginVcWithMessage:@"您的账号在另一台设备登录，请重新登录。"];
    }
    
}
-(void)laHeiReslove
{
    if ([SYUserInformation sharedInstance].isLogin) {
        [self presentLoginVcWithMessage:@"您的账号已被冻结无法登录"];
    }
}
- (void)presentLoginVcWithMessage:(NSString *)message
{
    LK(weakSelf)
    //被踢的通知
    _alertCount ++ ;
    
    if (_alertCount == 1) {
        _alertCount = 0;
        
        
        PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:message ButtonTitle:@"重新登录" ButtonClickBlock:^{
            YDLoginController *loginVC = [[YDLoginController alloc] init];
            loginVC.loginStyle = Login_Present;
            YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
            [weakSelf presentViewController:baseNav animated:YES completion:nil];
            [weakSelf.pz_popupController dismiss];
        }];
        
        
        //影藏小红点
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowRedPointNoti object:@(NO)];
        [[SYUserDataManger sharedInstance] deleteUserDataTable];
        [SYUserInformation sharedInstance].isLogin = NO;
        
        
        self.pz_popupController = [[PZPopUpController alloc] init];
        [self.pz_popupController dropAnimatedWithRotateAngle:30];
        [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
    }
    
    
}

//是否隐藏小红点
- (void)showRedPoint:(NSNotification *)noti
{
    if([noti.object boolValue])
    {
        [self.tabBar showBadgeAtItemIndex:4];
    }else
    {
        [self.tabBar hideBadgeAtItemIndex:4];
    }
    
}
//点买成功通知
- (void)buySuccess:(NSNotification *)noti
{
//    self.selectedIndex = 1;
}

- (void)optionsBuySuccess:(NSNotification *)noti
{
    self.selectedIndex = 1;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //添加所有子控制器
    [self setUpAllChildsViewControllers];
    //设置tabbar上按钮的图片及文字
    [self setUpAllTabbarItemsTitle];
    [self setUpTab];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}


#pragma mark 替换系统的TabBar
-(void)setUpTab
{
    
    YDTabBar *tabBar = [[YDTabBar alloc] init];
    
    UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageWithColor:NumberColor(255, 255 , 255)]];
    
    img.frame = CGRectMake(0, 0, self.tabBar.frame.size.width, self.tabBar.frame.size.height + 34);
    img.contentMode = UIViewContentModeScaleToFill;
    [tabBar insertSubview:img atIndex:0];
    [self setValue:tabBar forKey:@"tabBar"];
}

#pragma mark 设置UITabBar上按钮的尺寸和字体
+(void)load
{
    //正常状态
    UITabBarItem *barItem = [UITabBarItem appearanceWhenContainedIn:self ,nil];
    NSMutableDictionary *norDict = [NSMutableDictionary dictionary];
    norDict[NSFontAttributeName] = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
    norDict[NSForegroundColorAttributeName] = NumberColor(178, 176, 179);;
    [barItem setTitleTextAttributes:norDict forState:UIControlStateNormal];
    
    //选中状态
    NSMutableDictionary *selDict = [NSMutableDictionary dictionary];
    selDict[NSFontAttributeName] = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
    selDict[NSForegroundColorAttributeName] = [UIColor blackColor];
    [barItem setTitleTextAttributes:selDict forState:UIControlStateSelected];
    
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

#pragma mark 添加所有子控制器
-(void)setUpAllChildsViewControllers
{
    //首页
    YDHomeViewController *homeViewController = [[YDHomeViewController alloc] init];
    YDBaseNavigationController *nav1 = [[YDBaseNavigationController alloc] initWithRootViewController:homeViewController];
    nav1.fullScreenPopGestureEnabled = YES;
    [self addChildViewController:nav1];

    
    //期权
    YDBaseOptionsViewController *optionaViewController = [[YDBaseOptionsViewController alloc] init];
    YDBaseNavigationController *nav2 = [[YDBaseNavigationController alloc] initWithRootViewController:optionaViewController];
    nav2.fullScreenPopGestureEnabled = YES;
    [self addChildViewController:nav2];
    
    
    //直播
    YDLiveViewController *liveViewController = [[YDLiveViewController alloc] init];
    YDBaseNavigationController *nav3 = [[YDBaseNavigationController alloc] initWithRootViewController:liveViewController];
    nav3.fullScreenPopGestureEnabled = YES;
    [self addChildViewController:nav3];

    //资讯
    YDNewsViewController *newsViewController = [[YDNewsViewController alloc] init];
    YDBaseNavigationController *nav4 = [[YDBaseNavigationController alloc] initWithRootViewController:newsViewController];
    nav4.fullScreenPopGestureEnabled = YES;
    [self addChildViewController:nav4];
    
    //我的
    YDMineViewController *mineViewController = [[YDMineViewController alloc] init];
    YDBaseNavigationController *nav5 = [[YDBaseNavigationController alloc] initWithRootViewController:mineViewController];
    nav5.fullScreenPopGestureEnabled = YES;
    [self addChildViewController:nav5];
    
    
}
#pragma mark 设置tabbar上按钮的图片及文字
-(void)setUpAllTabbarItemsTitle
{
    //
    YDBaseNavigationController *nav0 = self.childViewControllers[0];
    nav0.tabBarItem.title = @"首页";
    nav0.tabBarItem.image = [UIImage imageWIthOriginalImage:@"yd_tab-shouye_nor"];
    nav0.tabBarItem.selectedImage = [UIImage imageWIthOriginalImage:@"yd_tab-shouye_sel"];
    
    //
    YDBaseNavigationController *nav1 = self.childViewControllers[1];
    nav1.tabBarItem.title = @"期权";
    nav1.tabBarItem.image = [UIImage imageWIthOriginalImage:@"yd_tab-qiquan-nor"];
    nav1.tabBarItem.selectedImage = [UIImage imageWIthOriginalImage:@"yd_tab-qiquan-sel"];
    
    
    YDBaseNavigationController *nav2 = self.childViewControllers[2];
    nav2.tabBarItem.title = @"直播";
    nav2.tabBarItem.image = [UIImage imageWIthOriginalImage:@"yd_tab-zhibo_nor"];
    nav2.tabBarItem.selectedImage = [UIImage imageWIthOriginalImage:@"yd_tab-zhibo_sel"];
    
    //
    YDBaseNavigationController *nav3 = self.childViewControllers[3];
    nav3.tabBarItem.title = @"资讯";
    nav3.tabBarItem.image = [UIImage imageWIthOriginalImage:@"yd_tab-zixun_nor"];
    nav3.tabBarItem.selectedImage = [UIImage imageWIthOriginalImage:@"yd_tab-zixun_sel"];
    
    //
    YDBaseNavigationController *nav4 = self.childViewControllers[4];
    nav4.tabBarItem.title = @"我的";
    nav4.tabBarItem.image = [UIImage imageWIthOriginalImage:@"yd_tab_wode_nor"];
    nav4.tabBarItem.selectedImage = [UIImage imageWIthOriginalImage:@"yd_tab_wode_sel"];
}

//- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
//{
//    NSInteger index = [self.tabBar.items indexOfObject:item];
//
//    if (index != self.currentIndex) {
//        [self animationFanZhuanIndex:index];
//    }
//}


-(void)animationFanZhuanIndex:(NSInteger)index
{
    
    NSMutableArray * tabbarbuttonArray = [NSMutableArray array];
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabbarbuttonArray addObject:tabBarButton];
        }
    }
    self.currentIndex = index;
    //只让图动
    UIView *view = (UIView *)tabbarbuttonArray[index];
    for (id obj in view.subviews) {
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
            UIView*parentView = (UIView *)obj;
            //获取当前画图的设备上下文
            CGContextRef context =UIGraphicsGetCurrentContext();
            //开始准备动画
            [UIView beginAnimations:nil context:context];
            //设置动画曲线，翻译不准，见苹果官方文档
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            [UIView setAnimationDuration:0.5];
            //动画效果
            //UIViewAnimationTransitionCurlDown 从上向下
            //UIViewAnimationTransitionCurlUp  从下向上
            //UIViewAnimationTransitionFlipFromLeft  从左向右
            //UIViewAnimationTransitionFlipFromRight  从右向左
            
            [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:parentView cache:YES];//从左向右
            
            [UIView setAnimationDelegate:self];
            
            //当动画执行结束，执行animationFinished方法
            [UIView setAnimationDidStopSelector:@selector(animationFinished:)];
            //提交动画
            [UIView commitAnimations];
        }
    }
    
}
- (void)animationFinished:(id)sender
{
    //放大
    NSMutableArray * tabbarbuttonArray = [NSMutableArray array];
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabbarbuttonArray addObject:tabBarButton];
        }
    }
    CABasicAnimation*scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnim.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    scaleAnim.duration = 0.1;
    scaleAnim.repeatCount= 1;
    scaleAnim.autoreverses= YES; //动画后执行动画前的状态
    scaleAnim.fromValue= [NSNumber numberWithFloat:0.9];
    scaleAnim.toValue= [NSNumber numberWithFloat:1.2];
    //只让图动
    UIView *view = (UIView *)tabbarbuttonArray[self.currentIndex];
    for (id obj in view.subviews) {
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
            [[obj layer] addAnimation:scaleAnim forKey:nil];
            
        }
    }
}

- (void)updateVersion
{
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:App_Store_UpdateInfo]];
    request.HTTPMethod = @"POST";
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data)
        {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSDictionary *infoDic = [obj objectForKey:@"results"];
            
            //获取最新版本
            NSString *newVersion = [[infoDic valueForKey:@"version"] firstObject];
            
            //获取更新说明
            //  NSString  *message = [[infoDic valueForKey:@"releaseNotes"] firstObject];
            
            
            //支持最小的版本号
            NSString *miniOs = [[infoDic valueForKey:@"minimumOsVersion"] firstObject];
            
            
            if (miniOs.length) {
                if([miniOs floatValue] > [[[UIDevice currentDevice] systemVersion] floatValue] ){
                    DDLog(@"系统版本过低，最新版本的应用不支持%@以下系统",miniOs);
                    return;
                }
            }
            
            
            //获取最新版本号
            int newV = [[newVersion stringByReplacingOccurrencesOfString:@"." withString:@""] intValue];
            
            
            //获取本地版本号
            int oldV = [[[SYUserInformation sharedInstance].appVersion stringByReplacingOccurrencesOfString:@"." withString:@""] intValue];
            
            if (newV > oldV)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self updateAlert];
                });
                
            }
            
        }
        
        
    }];
    
    [dataTask resume];
}
-(void)checkVersionInformation
{
    //获取版本信息
    NSInteger localVersion = [[NSString stringWithFormat:@"%@" , localVersionNumber] integerValue];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setObject:[NSNumber numberWithInteger:localVersion] forKey:@"versionCode"];
    [dict setObject:[NSNumber numberWithInteger:[deviceType integerValue]] forKey:@"deviceType"];
    [dict setObject:[NSNumber numberWithInteger:[shellIndex integerValue]] forKey:@"shellIndex"];
    
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:GetAppVersionInformation WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"resultDict = %@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            if ([resultDict[@"result"] count]) {
                NSString *urlString = [NSString stringWithFormat:@"%@" , resultDict[@"result"][@"downloadLink"]];
                [self upDatePostViewWithUrl:urlString];
                
            }
        }
    } failBlock:^(NSError *error) {
        
    }];
    
    
    
}
-(void)upDatePostViewWithUrl:(NSString *)urlString
{
    LK(weakSelf)
    PZTipsOverFlyView *alert=  [PZTipsViewManger shareImageTipsOverFlyViewTitle:@"" SubTitle:@"发现新版本" Mesage:@"检测到有新版本，为了您更好的使用软件，请立即更新!否则可能会引起部分功能无法正常使用！" CancleTitle:nil SureTitle:@"立即更新" CancleBlock:^{
        
        
    } SureBlock:^{
        [weakSelf.pz_popupController dismiss];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        
    }];
    
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    self.pz_popupController.isNotResponseTap = YES;
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}
- (void)updateAlert
{
    
    PZTipsOverFlyView *alert=  [PZTipsViewManger shareImageTipsOverFlyViewTitle:@"" SubTitle:@"发现新版本" Mesage:@"检测到有新版本，为了您更好的使用软件，请立即更新!否则可能会引起部分功能无法正常使用！" CancleTitle:nil SureTitle:@"立即更新" CancleBlock:^{
        
        
    } SureBlock:^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:App_Store_Url]];
        [self.pz_popupController dismiss];
    }];
    
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    self.pz_popupController.isNotResponseTap = YES;
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
    
}
@end
